'use strict'

const { ApiController } = require('jax')
const dayjs = require('dayjs')

class Controller extends ApiController {
  // 模型
  get Model() {
    return this.ctx.model.Activity
  }

  // 可预约日期
  async getActivityDate() {
    const { ctx } = this
    const { query } = ctx

    if (!query.storeId) throw new Error('storeId is required')

    const startDate = query.startDate || dayjs().format('YYYY-MM-DD')
    const endDate = query.endDate || dayjs().add(1, 'M').format('YYYY-MM-DD')

    const results = await this.Model.aggregate([
      {
        $match: {
          isOpen: true,
          activityDate: {
            $gte: new Date(`${startDate} 00:00:00`),
            $lt: new Date(`${endDate} 23:59:59`),
          },
          status: 0,
        },
      },
      {
        $group: {
          _id: '$activityDate',
          activityCount: { $sum: 1 },
        },
      },
    ])

    ctx.body = {
      code: 0,
      msg: 'success',
      data: results.map((item) => {
        return {
          activityDate: dayjs(item._id).format('YYYY-MM-DD'),
          activityCount: item.activityCount,
        }
      }),
    }
  }

  // 活动时间段
  async getActivityTime() {
    const { ctx } = this
    const { helper, query } = ctx

    helper.validate(query, {
      include: ['storeId', 'activityDate'],
    })

    const results = await this.Model.find({
      activityDate: query.activityDate,
      storeId: query.storeId,
      isOpen: true,
    }).sort({
      startTime: 1,
    })

    console.log('results', results)

    ctx.body = {
      code: 0,
      msg: 'success',
      data: results.map((item) => {
        console.log('item.startTime', item.startTime)
        console.log('item.endTime', item.endTime)

        return {
          activityId: item.id,
          status: item.status,
          // startTime: dayjs(item.startTime).format('HH:mm'),
          // endTime: dayjs(item.endTime).format('HH:mm'),
          startTime: item.startTime,
          endTime: item.endTime,
        }
      }),
    }
  }
}

module.exports = Controller
